from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Dict, Any, List, Optional
from datetime import datetime, timedelta
import json

from app.api import deps
from app.models.generation_job import GenerationJob, JobStatus
from app.tasks.enhanced_generation_tasks import enhanced_generate_video_task, enhanced_generate_image_task, batch_generation_task
from app.celery_app import celery_app
from celery.result import AsyncResult

router = APIRouter()

@router.get("/tasks/{task_id}/status")
async def get_task_status(
    task_id: str,
    current_user = Depends(deps.get_current_user_optional)
):
    """获取Celery任务状态"""
    
    try:
        result = AsyncResult(task_id, app=celery_app)
        
        task_info = {
            "task_id": task_id,
            "status": result.status,
            "ready": result.ready(),
            "successful": result.successful() if result.ready() else None,
            "failed": result.failed() if result.ready() else None,
            "timestamp": datetime.now().isoformat()
        }
        
        # 获取任务结果或错误信息
        if result.ready():
            if result.successful():
                task_info["result"] = result.result
            else:
                task_info["error"] = str(result.info)
        else:
            # 获取进度信息
            if result.info and isinstance(result.info, dict):
                task_info["progress"] = result.info
        
        return task_info
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取任务状态失败: {str(e)}")

@router.get("/tasks/{task_id}/progress")
async def get_task_progress(
    task_id: str,
    current_user = Depends(deps.get_current_user_optional)
):
    """获取任务详细进度"""
    
    try:
        result = AsyncResult(task_id, app=celery_app)
        
        if not result.ready() and result.info and isinstance(result.info, dict):
            return {
                "task_id": task_id,
                "status": result.status,
                "progress": result.info.get("current", 0),
                "total": result.info.get("total", 100),
                "percentage": result.info.get("current", 0),
                "message": result.info.get("status", "处理中..."),
                "job_id": result.info.get("job_id"),
                "timestamp": datetime.now().isoformat()
            }
        elif result.ready():
            return {
                "task_id": task_id,
                "status": result.status,
                "progress": 100,
                "total": 100,
                "percentage": 100,
                "message": "任务完成" if result.successful() else "任务失败",
                "result": result.result if result.successful() else None,
                "error": str(result.info) if result.failed() else None,
                "timestamp": datetime.now().isoformat()
            }
        else:
            return {
                "task_id": task_id,
                "status": result.status,
                "progress": 0,
                "total": 100,
                "percentage": 0,
                "message": "任务排队中...",
                "timestamp": datetime.now().isoformat()
            }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取任务进度失败: {str(e)}")

@router.post("/tasks/generate-video")
async def create_video_generation_task(
    job_id: int,
    provider: Optional[str] = None,
    current_user = Depends(deps.get_current_user),
    db: Session = Depends(deps.get_db)
):
    """创建视频生成任务"""
    
    try:
        # 验证任务归属
        job = db.query(GenerationJob).filter(
            GenerationJob.id == job_id,
            GenerationJob.user_id == current_user.id
        ).first()
        
        if not job:
            raise HTTPException(status_code=404, detail="任务不存在或无权限访问")
        
        # 启动异步任务
        task = enhanced_generate_video_task.delay(job_id, provider)
        
        return {
            "task_id": task.id,
            "job_id": job_id,
            "provider": provider,
            "status": "started",
            "message": "视频生成任务已启动",
            "timestamp": datetime.now().isoformat()
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建任务失败: {str(e)}")

@router.post("/tasks/generate-image")
async def create_image_generation_task(
    job_id: int,
    provider: Optional[str] = None,
    current_user = Depends(deps.get_current_user),
    db: Session = Depends(deps.get_db)
):
    """创建图片生成任务"""
    
    try:
        # 验证任务归属
        job = db.query(GenerationJob).filter(
            GenerationJob.id == job_id,
            GenerationJob.user_id == current_user.id
        ).first()
        
        if not job:
            raise HTTPException(status_code=404, detail="任务不存在或无权限访问")
        
        # 启动异步任务
        task = enhanced_generate_image_task.delay(job_id, provider)
        
        return {
            "task_id": task.id,
            "job_id": job_id,
            "provider": provider,
            "status": "started",
            "message": "图片生成任务已启动",
            "timestamp": datetime.now().isoformat()
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建任务失败: {str(e)}")

@router.post("/tasks/batch-generate")
async def create_batch_generation_task(
    job_ids: List[int],
    provider: Optional[str] = None,
    current_user = Depends(deps.get_current_user),
    db: Session = Depends(deps.get_db)
):
    """创建批量生成任务"""
    
    try:
        # 验证所有任务归属
        jobs = db.query(GenerationJob).filter(
            GenerationJob.id.in_(job_ids),
            GenerationJob.user_id == current_user.id
        ).all()
        
        if len(jobs) != len(job_ids):
            raise HTTPException(status_code=400, detail="部分任务不存在或无权限访问")
        
        # 启动批量任务
        task = batch_generation_task.delay(job_ids, provider)
        
        return {
            "task_id": task.id,
            "job_ids": job_ids,
            "job_count": len(job_ids),
            "provider": provider,
            "status": "started",
            "message": f"批量生成任务已启动，包含{len(job_ids)}个子任务",
            "timestamp": datetime.now().isoformat()
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建批量任务失败: {str(e)}")

@router.post("/tasks/{task_id}/cancel")
async def cancel_task(
    task_id: str,
    current_user = Depends(deps.get_current_user_optional)
):
    """取消任务"""
    
    try:
        result = AsyncResult(task_id, app=celery_app)
        
        if result.ready():
            return {
                "task_id": task_id,
                "status": "already_finished",
                "message": "任务已完成，无法取消"
            }
        
        # 撤销任务
        result.revoke(terminate=True)
        
        return {
            "task_id": task_id,
            "status": "cancelled",
            "message": "任务已取消",
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"取消任务失败: {str(e)}")

@router.get("/tasks/active")
async def get_active_tasks(
    current_user = Depends(deps.get_current_user_optional)
):
    """获取活跃任务列表"""
    
    try:
        # 获取活跃任务
        active_tasks = celery_app.control.inspect().active()
        
        if not active_tasks:
            return {
                "active_tasks": [],
                "total_workers": 0,
                "total_tasks": 0
            }
        
        all_tasks = []
        for worker, tasks in active_tasks.items():
            for task in tasks:
                all_tasks.append({
                    "task_id": task.get("id"),
                    "name": task.get("name"),
                    "worker": worker,
                    "args": task.get("args", []),
                    "kwargs": task.get("kwargs", {}),
                    "time_start": task.get("time_start")
                })
        
        return {
            "active_tasks": all_tasks,
            "total_workers": len(active_tasks),
            "total_tasks": len(all_tasks),
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取活跃任务失败: {str(e)}")

@router.get("/tasks/stats")
async def get_task_stats(
    current_user = Depends(deps.get_current_user_optional)
):
    """获取任务统计信息"""
    
    try:
        stats = celery_app.control.inspect().stats()
        
        if not stats:
            return {
                "workers": 0,
                "total_stats": {}
            }
        
        # 聚合统计信息
        total_stats = {
            "total_workers": len(stats),
            "total_tasks": 0,
            "pool_processes": 0
        }
        
        worker_details = []
        for worker, worker_stats in stats.items():
            total_stats["total_tasks"] += worker_stats.get("total", {}).get("tasks.total", 0)
            total_stats["pool_processes"] += worker_stats.get("pool", {}).get("max-concurrency", 0)
            
            worker_details.append({
                "worker": worker,
                "status": "online",
                "total_tasks": worker_stats.get("total", {}).get("tasks.total", 0),
                "processes": worker_stats.get("pool", {}).get("max-concurrency", 0)
            })
        
        return {
            "summary": total_stats,
            "workers": worker_details,
            "timestamp": datetime.now().isoformat()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取任务统计失败: {str(e)}")